<?php

namespace app\agent\controller\stat;

use app\agent\controller\Controller;
use think\facade\Db;

class Mobile extends Controller
{
    /**
     * 列表.
     */
    public function successRate()
    {
        // 是否刷新最新数据
        $refresh = input('post.refresh', 0);

        $cacheKey = 'agent.stat.mobile.successRate';
        $cacheVal = cache($cacheKey);
        if (!$refresh && !empty($cacheVal['data'])) {
            return success('操作成功', $cacheVal);
        }

        $supplierIds = Db::name('agent_mobile_supplier')
            ->where('agent_id', $this->agent['id'])
            ->column('mobile_supplier_id');
        $supplierList = Db::name('mobile_supplier')
            ->where('is_deleted', 0)
            ->whereIn('id', $supplierIds)
            ->column('yidong_fast, liantong_fast, dianxin_fast', 'id');
        $supplierStatus = [
            'yidong_fast' => [],
            'liantong_fast' => [],
            'dianxin_fast' => [],
        ];
        foreach ($supplierList as $v) {
            foreach ($v as $field => $value) {
                if (!isset($supplierStatus[$field])) {
                    continue;
                }
                $supplierStatus[$field] = array_merge($supplierStatus[$field], json_decode($value));
            }
        }
        unset($supplierIds);
        unset($supplierList);

        $ispTypeList = [
            1 => [
                'name' => '移动',
                'key' => 'yidong_fast',
            ],
            2 => [
                'name' => '联通',
                'key' => 'liantong_fast',
            ],
            3 => [
                'name' => '电信',
                'key' => 'dianxin_fast',
            ],
        ];
        $amountList = [30, 50, 100, 200];
        $tmp = [];
        foreach ($ispTypeList as $ispType => $ispName) {
            if ($ispType == -1) {
                continue;
            }
            foreach ($amountList as $amount) {
                $tmp[$ispType][$amount]['success'] = 0;
                $tmp[$ispType][$amount]['total'] = 0;
            }
        }

        $list = Db::name('mobile_order_stats')
            ->field('id, isp_type, amount, status, supplier_id, agent_id')
            ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 30 * 60)) // 30分钟成功率
            ->where('agent_id', $this->agent['id'])
            ->cursor();
        foreach ($list as $v) {
            $tmp[$v['isp_type']][$v['amount']]['total'] += 1;
            if ($v['status'] == 1) {
                $tmp[$v['isp_type']][$v['amount']]['success'] += 1;
            }
        }

        $data = [];
        $id = 1;
        foreach ($tmp as $ispType => $v1) {
            $t = [
                'id' => $id++,
                'isp_name' => $ispTypeList[$ispType]['name'],
            ];
            $key = $ispTypeList[$ispType]['key'];
            foreach ($v1 as $amount => $v2) {
                if (!in_array($amount, $supplierStatus[$key])) {
                    $t['amount_' . $amount] = '维护';
                    continue;
                }
                if (empty($v2['total'])) {
                    $t['amount_' . $amount] = '--';
                    continue;
                }

                $rate = $v2['success'] / $v2['total'] * 100;
                // 代理成功率加成规则：
                // 成功率<10%，随机增加3%~5%；
                // 成功率>=10%,<90%，随机增加5%~15%，最高不超过95%；
                // 成功率>=90%，不加成，显示真实成功率；
                if ($rate < 10) {
                    $rate += random_int(3, 5);
                } elseif ($rate < 90) {
                    $rate += random_int(5, 15);
                    $rate = min(95, $rate);
                }
                $rate = number_format($rate, 2);
                $t['amount_' . $amount] = $rate . '%';
            }
            $data[] = $t;
        }
        unset($tmp);

        $cacheVal = [
            'data' => $data,
            'agent_id' => $this->agent['id'],
            'stat_time' => date('Y-m-d H:i:s'),
        ];
        cache($cacheKey, $cacheVal, 300); // 缓存 5 分钟

        return success('操作成功', $cacheVal);
    }
}
